import json
import re
from django.http import JsonResponse
from django.views import View
from focus_on_rent.libs.qiniuyun.qiniuyun.qiniu_storage import storage
from focus_on_rent.settings import dev
from focus_on_rent.utils.views import LoginRequiredMixin
from django.utils import timezone  # 引入timezone模块


class UserInfoView(LoginRequiredMixin, View):
    """用户信息"""

    def get(self, request):
        # 获取界面需要的数据,进行拼接
        # 获取现在时间
        create_time = timezone.now().strftime("%Y-%m-%d %H:%M:%S")
        print(create_time)
        # 获取数据
        info_data = {
            'avatar': str(request.user.avatar),
            'create_time': create_time,
            'mobile': request.user.mobile,
            'name': request.user.username,
            'user_id': request.session.get("_auth_user_id")
        }
        # 返回参数
        return JsonResponse({
            'errno': 0,
            'errmsg': 'OK',
            'data': info_data
        })


class AvatarActiveView(LoginRequiredMixin, View):
    """用户上传头像"""

    def post(self, request):
        # 接收参数
        image = request.FILES.get('avatar')
        a = image.read()

        # 判断前段是否上传图片
        if a is None:
            return JsonResponse({
                'errno': '4002',
                'errmsg': '头像上传失败'
            })
        # 调七牛云函数
        url_key = storage(a)
        avatar_url = dev.QINIU_URL + url_key
        try:
            # 将头像地址上传到数据库
            request.user.avatar = avatar_url
            request.user.save()
        except Exception as e:
            return JsonResponse({
                'errno': '4001',
                'errmsg': '头像地址存储失败'
            })
        return JsonResponse({
            "data": {
                "avatar_url": avatar_url
            },
            'errno': '0',
            'errmsg': '头像上传成功'
        })


class ChangeUsernameView(LoginRequiredMixin, View):
    def put(self, request):
        """实现修改密码逻辑"""
        # 接收参数
        dict = json.loads(request.body.decode())
        name = dict.get('name')

        # 校验参数
        if name is None:
            return JsonResponse({
                'errno': '4002',
                'errmsg': '缺少必传参数'
            })
        try:
            # 将头像地址上传到数据库
            request.user.username = name
            request.user.save()
        except Exception as e:
            return JsonResponse({
                'errno': '4001',
                'errmsg': '用户名修改失败'
            })

        return JsonResponse({
            'errno': '0',
            'errmsg': '修改成功'
        })


class RealNameAuthenticationView(LoginRequiredMixin, View):
    """实名认证,只能认证一次"""

    def post(self, request):
        dict = json.loads(request.body.decode())
        real_name = dict.get('real_name')
        id_card = dict.get('id_card')
        if not all([real_name, id_card]):
            return JsonResponse({
                'errno': '4002',
                'errmsg': '缺少必传参数'
            })
        # 身份证正则
        if not re.match(r'^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$',
                        id_card):
            return JsonResponse({
                'errno': '4002',
                'errmsg': '身份证输入有误'
            })
        try:
            request.user.real_name = real_name
            request.user.id_card = id_card
            request.user.save()
        except Exception as e:
            return JsonResponse({'errno': 4001,
                                 'errmsg': '保存到数据库出错'})
        return JsonResponse({
            'errno': '0',
            'errmsg': '认证信息保存成功'
        })

    def get(self, request):
        real_name = request.user.real_name
        id_card = request.user.id_card
        data = {'real_name':real_name,
                'id_card':id_card}
        return JsonResponse({
            'errno': '0',
            'errmsg': '已经认证',
            'data': data
        })
